<template>
  <div class="upload-file">
    <el-upload
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :data="data"
      :on-error="handleUploadError"
      :on-success="handleUploadSuccess"
      :show-file-list="false"
      :headers="headers"
      class="upload-file-uploader"
      ref="fileUpload"
      v-if="!disabled"
    >
      <!-- 上传按钮 -->
      <el-button type="primary">选取PDF文件</el-button>
    </el-upload>
    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip && !disabled">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      格式为 <b style="color: #f56c6c">PDF</b> 的文件
    </div>
    <!-- 文件列表 -->
    <div v-if="fileList.length > 0" class="upload-file-list el-upload-list el-upload-list--text">
      <div class="el-upload-list__item ele-upload-list__item-content">
        <el-link :href="`${baseUrl}${fileList[0].url}`" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(fileList[0].name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action" v-if="!disabled">
          <el-link :underline="false" @click="handleDelete" type="danger">&nbsp;删除</el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth"

const props = defineProps({
  modelValue: [String, Object],
  // 上传接口地址
  action: {
    type: String,
    default: "/common/upload/pdf"
  },
  // 上传携带的参数
  data: {
    type: Object
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  // 禁用组件（仅查看文件）
  disabled: {
    type: Boolean,
    default: false
  }
})

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const baseUrl = import.meta.env.VITE_APP_BASE_API
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + props.action) // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() })
const fileList = ref([])
const showTip = computed(
  () => props.isShowTip && props.fileSize
)

watch(() => props.modelValue, val => {
  if (val) {
    if (typeof val === "string") {
      fileList.value = [{ name: val, url: val }]
    } else {
      fileList.value = [val]
    }
  } else {
    fileList.value = []
  }
},{ deep: true, immediate: true })

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  const fileName = file.name.split('.')
  const fileExt = fileName[fileName.length - 1].toLowerCase()
  if (fileExt !== 'pdf') {
    proxy.$modal.msgError(`文件格式不正确，请上传PDF格式文件!`)
    return false
  }
  // 校检文件名是否包含特殊字符
  if (file.name.includes(',')) {
    proxy.$modal.msgError('文件名不正确，不能包含英文逗号!')
    return false
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`)
      return false
    }
  }
  proxy.$modal.loading("正在上传文件，请稍候...")
  return true
}

// 上传失败
function handleUploadError(err) {
  proxy.$modal.msgError("上传文件失败")
  proxy.$modal.closeLoading()
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    fileList.value = [{ name: res.fileName, url: res.fileName }]
    emit("update:modelValue", res.fileName)
    proxy.$modal.closeLoading()
  } else {
    proxy.$modal.closeLoading()
    proxy.$modal.msgError(res.msg)
    proxy.$refs.fileUpload.handleRemove(file)
  }
}

// 删除文件
function handleDelete() {
  fileList.value = []
  emit("update:modelValue", "")
}

// 获取文件名称
function getFileName(name) {
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1)
  } else {
    return name
  }
}
</script>

<style scoped>
.upload-file-uploader { margin-bottom: 5px; }
.upload-file-list .el-upload-list__item { border: 1px solid #e4e7ed; line-height: 2; margin-bottom: 10px; position: relative; }
.upload-file-list .ele-upload-list__item-content { display: flex; justify-content: space-between; align-items: center; padding: 0 10px; }
</style>